<template>
	<view class="page">
		<navbar backIconName="arrow-left" :title="titleContent" :titleStyle="titleStyle"></navbar>
		<scroll-view class="scroll-view_H" scroll-y="true">
			<view :style="{height:statusHeight+'px'}"></view>

			<view class="inCompany-task">
				<view class="task-item">
					<view class="left">
						<u--form labelPosition="left" :model="formData" :rules="rules" labelWidth="90"
							:labelStyle="{fontSize:'26rpx',color:'#323232',fontWeight:'bold'}" ref="uForm">
							<u-form-item label="心声类型" prop="typeName" borderBottom>
								<u--input v-model="formData.typeName" disabled disabledColor="#ffffff" placeholder="请选择"
									border="none"></u--input>
								<!-- <u-icon slot="right" name="arrow-right"></u-icon> -->
							</u-form-item>
							<!-- <u-form-item label="系统领域" prop="systemDomain" borderBottom @click="openSystemDomainPop">
								<u--input v-model="formData.systemDomain" disabled disabledColor="#ffffff"
									placeholder="请选择" border="none"></u--input>
								<u-icon slot="right" name="arrow-right"></u-icon>
							</u-form-item> -->
							<!-- <u-form-item label="所属地区" prop="arears" borderBottom
								@click="lotusAddressData.visible = true;">
								<u--input v-model="formData.arears" disabled disabledColor="#ffffff" placeholder="请选择"
									border="none"></u--input>
								<u-icon slot="right" name="arrow-right"></u-icon>
							</u-form-item> -->
							<u-form-item label="所在区域" prop="addressName" borderBottom @click="showLegalPerson = true;">
								<u--input v-model="formData.addressName" disabled disabledColor="#ffffff"
									placeholder="请选择" border="none"></u--input>
								<u-icon slot="right" name="arrow-right"></u-icon>
							</u-form-item>
							<u-form-item label="倾诉对象" prop="departmentName" borderBottom @click="openDeptPop">
								<u--input v-model="formData.departmentName" disabled disabledColor="#ffffff"
									placeholder="请选择" border="none"></u--input>
								<u-icon slot="right" name="arrow-right"></u-icon>
							</u-form-item>
							<u-form-item label="反映内容" prop="reflectComment" borderBottom>
								<u--textarea v-model="formData.reflectComment" :showConfirmBar="false" count
									adjustPosition></u--textarea>
							</u-form-item>
							<u-form-item label="附件">
								<view
									style="font-size: 26rpx; display: flex;align-items: center;justify-content: space-between;">
									<text style="font-size: 22rpx;">最多支持5个文件，最大2M</text>
									<text class="custom-button" @click="selectFile">新增附件</text>
								</view>
							</u-form-item>
							<view class="file-content">
								<view class="item" v-for="(item,index) in fileList" :key="index">
									<text>{{item.name}}</text>
									<u-icon name="close" @click="del(item,index)"></u-icon>
								</view>
							</view>
							<u-form-item label="联系人" prop="contacts" borderBottom>
								<u--input v-model="formData.contacts" placeholder="请输入联系人" border="none"></u--input>
							</u-form-item>
							<u-form-item label="手机号" prop="contactNumber" borderBottom>
								<u-input v-model="formData.contactNumber" type="number" maxlength="11"
									placeholder="请输入手机号" border="none">
									<template slot="suffix">
										<view v-if="isPhoneCode" @click="getMsgCode" class="custom-button">
											<text>获取验证码</text>
										</view>
										<view v-else class="custom-button">
											<text>{{countDownPhone+'s'}}</text>
										</view>
									</template>
								</u-input>
							</u-form-item>
							<u-form-item label="短信验证码" prop="msgCode" borderBottom>
								<u--input v-model="formData.msgCode" type="number" placeholder="请输入短信验证码"
									border="none"></u--input>
							</u-form-item>
						</u--form>

					</view>

				</view>

			</view>
			<view class="submit-content">
				<u-button :throttleTime="1000" type="primary" text="提交" @click="submitTaskOver"></u-button>
			</view>

		</scroll-view>

		<u-action-sheet :show="showType" :actions="actions" round="12" title="请选择心声类型" @close="showType = false"
			@select="typeSelect">
		</u-action-sheet>

		<!-- 倾诉对象所在区域 -->
		<u-picker :show="showLegalPerson" ref="uPickerArear" :columns="columnsArear" keyName="name"
			@confirm="confirmArear" @change="changeHandlerArear" @cancel="showLegalPerson = false"></u-picker>
		<!-- 倾诉对象 -->
		<u-picker :show="showDept" :columns="columnsDept" keyName="deptName" @confirm="confirmDept"
			@cancel="showDept = false"></u-picker>

		<!-- 系统领域 -->
		<u-picker :show="showSystemDomain" :columns="columnsSystemDomain" keyName="name" @confirm="confirmSystemDomain"
			@cancel="showSystemDomain = false"></u-picker>


		<!-- 省市县三级联动 -->
		<!-- <lotus-address ref="lotus" v-on:choseVal="choseValue" :lotusAddressData="lotusAddressData"></lotus-address> -->

		<!-- 填报须知 -->
		<u-popup :show="showKnown" :round="5" mode="center" :safeAreaInsetBottom="false" @close="close">
			<view class="user-notice">
				<text class="title">填报须知</text>
				<view class="contains">
					<text class="content">（一）在写信活动中应遵守宪法、法律、法规和社会公德，如实反映情况，用语须文明、友善，不得捏造、歪曲事实，诽谤、诬告、陷害他人。</text>
					<text class="content">（二）请在来信中注明您的真实姓名、联系地址、电子信箱和联系方式,以便相关部门核实具体情况。</text>
					<text
						class="content">（三）信件标题要点明主要问题，内容必须实事求是，时间、地点、当事人、主要经过、结果等要素要齐全，文字简明扼要，说清事实，一信一事，以便相关部门展开具体的调查和处理。</text>
				</view>

				<view style="display: flex;width: 100%;margin-top: 30rpx;">
					<u-button v-if="isClick" type="primary" disabled :text="'确认填报'+countDownKnow + 's'"
						@click="showKnown = false"></u-button>
					<u-button v-else type="primary" text="确认填报" @click="showKnown = false"></u-button>
				</view>

			</view>
		</u-popup>


		<!-- loading -->
		<u-overlay :show="showLoading" :opacity="0.8">
			<view class="warp">
				<text style="font-size: 28rpx;color: #fff;">上传中...</text>
			</view>
		</u-overlay>


	</view>
</template>

<script>
	import {
		checkDate,
		checkProv,
		checkParity,
		checkPhone,
		toast,
		showConfirm,
	} from "@/utils/common.js"
	import {
		getDict,
	} from "@/api/login.js"
	import {
		treeseDepart,
		listDeptAll,
		submitHeart,
	} from '@/api/pagesMall'
	import {
		sendSmsCode,
	} from '@/api/pagesMine'
	let App = getApp();
	// import lotusAddress from "@/components/Winglau14-lotusAddress/Winglau14-lotusAddress.vue";
	import store from '@/store'
	import config from '@/api/config'
	export default {
		components: {
			// lotusAddress,
		},
		data() {
			return {
				showLoading: false,
				statusHeight: 44 + App.globalData.statusBarHeight,
				showKnown: true,
				titleStyle: {
					color: "#ffffff",
					fontWeight: "bold",
					fontSize: "18px"
				},
				titleContent: '',
				formData: {
					reflectComment: "",
					typeId: "",
					typeName: "",
					msgCode: "",
					addressId: "",
					addressName: "",
					systemDomain: "",
					contacts: "",
					contactNumber: "",
					departmentCode: "",
					departmentName: "",
					companyName: "",
					socialCreditNumber: "",
					attachmentDtoList: [],
				},
				rules: {
					addressName: [{
						required: true,
						message: '请选择所在区域',
						trigger: ['blur']
					}],
					departmentName: [{
						required: true,
						message: '请选择倾诉对象',
						trigger: ['blur']
					}],
					reflectComment: [{
						required: true,
						message: '请输入反应内容',
						trigger: ['blur']
					}],
					contacts: [{
						required: true,
						message: '请输入联系人',
						trigger: ['blur']
					}],
					contactNumber: [{
						required: true,
						message: '请输入手机号',
						trigger: ['blur']
					}, {
						// 自定义验证函数
						validator: (rule, value, callback) => {
							var checkID = (value) => {
								if (checkPhone(value)) {
									return true;
								} else {
									return false
								}
							}
							return checkID(value);
						},
						message: '手机号格式不正确',
						// 触发器可以同时用blur和change
						trigger: ['blur'],
					}],
					msgCode: [{
						required: true,
						message: '请输入短信验证码',
						trigger: ['blur']
					}],
				},
				showType: false,
				actions: [{
						name: '意见建议',
						id: 1,
					},
					{
						name: '我的求助',
						id: 2,
					},
				],
				lotusAddressData: {
					visible: false,
					provinceName: '',
					cityName: '',
					townName: '',
				},
				showLegalPerson: false,
				legalPersonActions: [{
						name: '是',
					},
					{
						name: '否',
					},
				],
				isPhoneCode: true,
				countDownPhone: 60,
				totalSecond: 60,
				timer1: null,
				columnsArear: [], //地市
				columnDataArear: [], //区县
				isClick: false,
				countDownKnow: 5,
				totalSecondKnow: 5,
				timer2: null,
				showDept: false,
				columnsDept: [],
				fileList: [],
				userId: store.state.user.USER_OPENID,
				currentCompanyInfo: store.state.user.COMPANY_INFO,
				showSystemDomain: false,
				columnsSystemDomain: [],
			};
		},
		created() {
			this.getAreas()
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.uForm.setRules(this.rules)
			this.formData.companyName = this.currentCompanyInfo.companyName
			this.formData.socialCreditNumber = this.currentCompanyInfo.socialCreditNumber
		},
		beforeDestroy() {
			clearInterval(this.timer1)
			clearInterval(this.timer2)
		},
		onLoad(options) {
			this.formData.typeId = options.type
			if (options.type == '1') {
				this.formData.typeName = '意见建议'
				this.titleContent = '意见建议'
			}
			if (options.type == '2') {
				this.formData.typeName = '我的求助'
				this.titleContent = '我的求助'
			}
			this.getKnown()
			// this.getSystemDomain()
		},
		methods: {
			/* 选择文件 */
			selectFile() {
				if (this.fileList.length >= 5) {
					return uni.$u.toast('最多支持选择5个文件')
				}
				let fileType = ['pdf', 'doc', 'xlsx', 'docx', 'xls']
				uni.chooseMessageFile({
					count: 1, //默认100
					type: 'file',
					extension: fileType,
					success: (res) => {
						console.log(res)
						if (res.tempFiles[0].size > 1024 * 1024 * 2) {
							return uni.$u.toast('文件大小不能超过2M')
						}
						if (this.fileList.find(item => item.name === res.tempFiles[0].name) != undefined) {
							return uni.$u.toast('存在重复附件')
						}
						this.showLoading = true
						uni.uploadFile({
							url: config.baseUrl + '/enterprise/upload/uploadFile',
							filePath: res.tempFiles[0].path,
							name: 'file',
							formData: {
								fileName: res.tempFiles[0].name,
								userId: this.userId,
							},
							success: (uploadFileRes) => {
								console.log('asdaggg', JSON.parse(uploadFileRes.data));
								this.showLoading = false
								let result = JSON.parse(uploadFileRes.data)
								if (result.code == 200 && result.data) {
									this.fileList.push({
										name: result.data.fileName,
										url: result.data.url
									})
								} else {
									return uni.$u.toast('上传失败，请重新上传')
								}

							},
							fail: (error) => {
								this.showLoading = false
								return uni.$u.toast('上传失败，请重新上传')
							}
						});


					}
				})
			},
			del(row, index) {
				this.fileList.splice(index, 1)
			},
			openDeptPop() {
				if (this.columnsDept.length == 0) {
					if (this.formData.addressName != '') {
						return uni.$u.toast('已选所在区域下未获取到倾诉对象')
					} else {
						return uni.$u.toast('请先选择所在区域')
					}
				}
				this.showDept = true
			},
			/* 选择系统领域 */
			openSystemDomainPop() {
				this.showSystemDomain = true
			},
			confirmSystemDomain(e) {
				this.formData.systemDomain = e.value[0].name
				this.showSystemDomain = false
			},
			getSystemDomain() {
				getDict('system_area').then(res => {
					let lists = res.data.map(item => {
						return {
							name: item.dictLabel,
							id: item.dictLabel
						}
					})
					lists.push({
						name: '其它',
						id: '其它'
					})
					this.columnsSystemDomain = [lists]
				});
			},
			/* 获取行政区划 */
			getAreas() {
				treeseDepart()
					.then(res => {
						let columnsArearData = []
						let dataList = []
						let lists = res.data.subList
						let columnDataArearData = []
						for (let i = 0; i < lists.length; i++) {
							if (lists[i].subList.length > 0) {
								dataList.push(lists[i])
								columnDataArearData.push(lists[i].subList)
							}
						}
						columnDataArearData.unshift({
							id: 1,
							name: '省直属'
						})
						columnsArearData.push(dataList)
						if (columnDataArearData.length > 0) {
							columnsArearData.push(columnDataArearData[0])
						}
						columnsArearData[0].unshift({
							id: 1,
							name: '省直属'
						})
						for (let i = 1; i < columnsArearData[0].length; i++) {
							columnDataArearData[i].unshift({
								id: columnsArearData[0][i].id,
								name: '市本级'
							})
						}

						this.columnsArear = columnsArearData
						this.columnDataArear = columnDataArearData
						console.log(this.columnsArear)
						console.log(this.columnDataArear)
					})
			},
			/* 倾诉对象所在区域 */
			changeHandlerArear(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPickerArear
				} = e
				// 当第一列值发生变化时，变化第二列(后一列)对应的选项
				if (columnIndex === 0) {
					// picker为选择器this实例，变化第二列对应的选项
					picker.setColumnValues(1, this.columnDataArear[index])
				}
				console.log('改变了')
			},
			// 回调参数为包含columnIndex、value、values
			confirmArear(e) {
				console.log(e)
				this.showLegalPerson = false
				if (e.value[1] == undefined) {
					this.formData.addressName = e.value[0].name
					this.formData.addressId = e.values[1].id
					this.getObject(e.values[1].id)
				} else {
					this.formData.addressName = e.value[0].name + '-' + e.value[1].name
					this.formData.addressId = e.value[1].id
					this.getObject(e.value[1].id)
				}
				this.formData.departmentName = ""
				this.formData.departmentCode = ""

			},
			/* 获取倾诉对象 */
			getObject(id) {
				listDeptAll({
					id: id
				}).then(res => {
					console.log(res, '+++++++++++++数据+++++++++++++')
					this.columnsDept = (res.data && res.data.length > 0) ? [res.data] : []
				})
			},
			confirmDept(e) {
				this.formData.departmentName = e.value[0].deptName
				this.formData.departmentCode = e.value[0].code
				this.showDept = false
			},
			close() {

			},
			/* 心声类型 */
			typeSelect(res) {
				console.log(res)
				this.formData.typeId = res.id
				this.formData.typeName = res.name
			},
			/* 提交 */
			submitTaskOver() {
				if(this.currentCompanyInfo == null){
					return uni.$u.toast('请先认证企业')
				}
				
				
				this.$refs.uForm.validate().then(res => {
					let userid = store.state.user.USER_OPENID
					let params = {
						reflectComment: this.formData.reflectComment,
						typeId: this.formData.typeId,
						typeName: this.formData.typeName,
						msgCode: this.formData.msgCode,
						addressId: this.formData.addressId,
						addressName: this.formData.addressName,
						contacts: this.formData.contacts,
						contactNumber: this.formData.contactNumber,
						departmentCode: this.formData.departmentCode,
						departmentName: this.formData.departmentName,
						companyName: this.formData.companyName,
						socialCreditNumber: this.formData.socialCreditNumber,
						attachmentDtoList: [],
						userId: userid
					}
					let fileList = this.fileList.map(item => {
						return {
							fileName: item.name || '',
							fileUrl: item.url || '',
							type: '',
						}
					})
					params.attachmentDtoList = fileList
					console.log(params, "************************")
					showConfirm('确认要提交' + this.titleContent + '？').then(res => {
						if (res.confirm) {
							submitHeart(params).then(res => {
								console.log(res)
								if (res.code == 200) {
									uni.$u.toast('提交成功！')
									uni.navigateBack()
								}

							});
						}
					})
				}).catch(errors => {

				})
			},
			// //打开picker
			// openPicker() {
			// 	this.lotusAddressData.visible = true;
			// 	// this.lotusAddressData.provinceName = '河南省';
			// 	// this.lotusAddressData.cityName = '郑州市';
			// 	// this.lotusAddressData.townName = '中原区';
			// },
			// //回传已选的省市区的值
			// choseValue(res) {
			// 	//res数据源包括已选省市区与省市区code
			// 	this.lotusAddressData.visible = res.visible; //visible为显示与关闭组件标识true显示false隐藏
			// 	//res.isChose = 1省市区已选 res.isChose = 0;未选
			// 	if (res.isChose) {
			// 		this.lotusAddressData.provinceName = res.province; //省
			// 		this.lotusAddressData.cityName = res.city; //市
			// 		this.lotusAddressData.townName = res.town; //区
			// 		this.formData.arears = `${res.province} ${res.city} ${res.town}`; //region为已选的省市区的值
			// 	}
			// },
			/* 获取验证码 */
			getMsgCode() {
				if (this.formData.contactNumber == '') {
					return uni.$u.toast('请填写手机号')
				}
				if (!checkPhone(this.formData.contactNumber)) {
					return uni.$u.toast('请填写正确的手机号')
				}
				// 当前目前没有定时器开着，且 totalSecond 和 second 一致 (秒数归位) 才可以倒计时
				if (!this.timer1 && this.countDownPhone === this.totalSecond) {
					this.isPhoneCode = false
					// 开启倒计时
					this.timer1 = setInterval(() => {
						this.countDownPhone--
						if (this.countDownPhone <= 0) {
							clearInterval(this.timer1)
							this.timer1 = null // 重置定时器 id
							this.countDownPhone = this.totalSecond // 归位
							this.isPhoneCode = true
						}
					}, 1000)
					// 发送请求，获取验证码
					let openId = this.$store.state.user.USER_OPENID
					sendSmsCode({
							phoneNumber: this.formData.contactNumber,
							userId: openId
						})
						.then(res => {
							// uni.$u.toast(res.data)
							uni.$u.toasst("发送成功!")
						})

				}
			},
			/* 须知倒计时 */
			getKnown() {
				if (!this.timer2 && this.countDownKnow === this.totalSecondKnow) {
					this.isClick = true
					// 开启倒计时
					this.timer2 = setInterval(() => {
						this.countDownKnow--
						if (this.countDownKnow <= 0) {
							clearInterval(this.timer2)
							this.timer2 = null // 重置定时器 id
							this.countDownKnow = this.totalSecondKnow // 归位
							this.isClick = false
						}
					}, 1000)
				}
			},
		}
	};
</script>

<style lang="scss" scoped>
	.warp {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
	}

	.file-content {
		.item {
			font-size: 24rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 12rpx 14rpx;
			border-radius: 8rpx;
			border: 1px solid #eee;
			margin-bottom: 10rpx;
		}
	}

	.custom-button {
		width: 160rpx;
		height: 54rpx;
		font-size: 24rpx;
		color: #fff;
		background: #3c9cff;
		border-radius: 6px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.attachmentList {
		padding: 20rpx 0px;
		font-size: 28rpx;
		color: #323232;

		.item {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			border-bottom: 1px solid #d6d7d9;
			padding: 10rpx 0rpx;
		}
	}

	.user-notice {
		width: 75vw;
		padding: 30rpx 36rpx;
		display: flex;
		flex-direction: column;
		align-items: center;

		.title {
			font-size: 30rpx;
			color: #323232;
			font-weight: bold;
			padding-bottom: 30rpx;
		}

		.contains {
			height: 40vh;
			overflow: auto;
			display: flex;
			flex-direction: column;

			.content {
				font-size: 26rpx;
				color: #666;
				text-indent: 24px;
				line-height: 38rpx;
			}
		}


	}

	.scroll-view_H {
		width: 100%;
		height: 100%;

		.submit-content {
			padding: 30rpx;
			height: 200rpx;
			display: flex;
			flex-direction: column;
			justify-content: space-around;
		}

		.inCompany-task {
			display: flex;
			flex-direction: column;
			padding: 20rpx;


			.task-item {
				display: flex;
				align-items: center;
				padding: 20rpx 30rpx;
				background-color: #fff;
				border-radius: 12rpx;
				box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.15);

				.left {
					flex: 1;
					display: flex;
					flex-direction: column;

					.top {
						display: flex;
						padding-bottom: 20rpx;

						.label-content {
							width: 240rpx;
							font-size: 28rpx;
							color: #323232;
							font-weight: bold;
						}
					}
				}
			}
		}



	}
</style>